<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <link rel="stylesheet" href="../../lib/yzhUpload/control/css/zyUpload.css" type="text/css">
    <style>
        body {
            background-color: #ffffff;
        }

        .aui-upload-box {
            background-color: #fff;
            width: 105px;
            height: 105px;
            padding-top: 5px;
            padding-right: 5px;
        }

        .chose_pic_btn {
            width: 95px;
            height: 95px;
            position: relative;
            display: inline-block;
            background-image: url('');
            box-sizing: border-box;
            background-size: 45px 45px;
            background-position: center center;
            background-repeat: no-repeat;
            background-color: #ededed;
            margin-left: 3.3333%;
            margin-bottom: 12px;
            border-radius: 5px;
        }

        .chose_pic_btn div {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
        }

        .cancel {
            width: 20px;
            height: 20px;
            line-height: 19px;
            border: 1px solid #dbd9d9;
            background-color: #dbd9d9;
            border-radius: 50%;
            position: absolute; /* 父组件赋予属性relative生效 */
            right: 0px; /* 使元素处于右上角-右 */
            top: 0px; /* 使元素处于右上角-上 */
        }

        .cancel::before,
        .cancel::after {
            content: "";
            position: absolute;
            height: 14px;
            width: 2px;
            top: 3px; /* 使X处于圆中心 */
            left: 9px; /* 使X处于圆中心 */
            background-color: #353535;
        }

        .cancel::before {
            transform: rotate(45deg);
        }

        .cancel::after {
            transform: rotate(-45deg);
        }

    </style>
</head>
<body>
<div class="layui-form layuimini-form" lay-filter="article-form">
    <div class="layui-form-item">
        <label class="layui-form-label required">文章编号</label>
        <div class="layui-input-block">
            <input type="text" name="id" lay-verify="required" lay-reqtext="文章编号为空" placeholder="请填写标题" value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">文章标题</label>
        <div class="layui-input-block">
            <input type="text" name="title" lay-verify="required" lay-reqtext="标题不能为空" placeholder="请填写标题" value=""
                   class="layui-input">
        </div>
    </div>

    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label required">缩略图</label>
        <div class="layui-input-block">
            <div class="layui-upload">
                <div class="aui-upload-box" onclick="addPic()">
                    <div class="aui-upload-pic">
					<span class="chose_pic_btn" id="mainDiagram">
						<div>
                        </div>
					</span>
                    </div>
                </div>
                <p id="errText"></p>
                <button type="button" class="layui-btn" id="upload-mainDiagram">上传图片</button>
            </div>
            <input type="text" style="display: none" name="image" lay-verify="required" lay-reqtext="缩略图不能为空"
                   value="" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">文章地址</label>
        <div class="layui-input-block">
            <input type="text" name="url" placeholder="请填写跳转地址" value="" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">自定义内容</label>
        <div class="layui-input-block">
            <div id="editor" style="margin: 5px 0 5px 0"></div>
            <button class="layui-btn layui-btn-danger" onclick="emptyDetails()">清空内容</button>
            <input type="text" name="content" value="" style="display: none" placeholder="请填写内容">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认修改</button>
        </div>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>

<script>

    let editor;

    window.onload = function () {
        let id = GetQueryString("id");
        if (isNotNull(id)) {
            init(id);
        } else {
            const iframeIndex = parent.layer.getFrameIndex(window.name);
            parent.layer.close(iframeIndex);
        }
    }

    /**
     * 初始化数据
     */
    function init(id) {
        $.ajax({
            type: "get",
            url: '/article/info/' + id,
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (req) {
                layui.use(['form'], function () {
                    let form = layui.form;
                    form.render();
                    form.val('article-form', {
                        "id": req.data.id,
                        "title": req.data.title,
                        "content": req.data.content,
                        "url": req.data.url,
                        "image": req.data.image,
                    });
                    if (isNotNull(req.data.content)) {
                        initEditor(req.data.content);
                    }
                    if (isNotNull(req.data.image)) {
                        if (isNotNull(req.data.image)) {
                            $('#mainDiagram').css({
                                'background-image': 'url(' + req.data.image + ')',
                                'background-size': '100% 100%'
                            }); //图片链接（base64）
                        }
                    }
                })
            },
            error: function (e) {
                layer.msg("数据有误");
            }
        })
    }

    layui.use(['layer', 'form'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.$;

        //监听提交
        form.on('submit(saveBtn)', function (data) {

            var index = layer.alert('确定提交修改吗？', {
                title: '提示'
            }, function () {
                let myMsg = layer.msg("正在提交...", {
                    icon: 16,
                    time: -1
                })
                $.ajax({
                    type: "post",
                    url: '/article/edit',
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json; charset=UTF-8',
                    success: function (req) {
                        if (req.code === '200') {
                            layer.msg("修改成功");
                            layer.close(index);
                            // 关闭弹出层
                            setTimeout(function () {
                                layer.close(myMsg);//手动关闭
                                let iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                                let parentWindow = window.parent;
                                parentWindow.reloadTable();
                            }, 1500);
                        } else {
                            layer.msg(req.msg);
                            layer.close(index);
                        }
                    },
                    error: function (e) {
                        layer.msg("修改失败");
                        layer.close(myMsg);//手动关闭
                    }
                })
            });
            return false;
        });

    });

    //常规使用 - 普通图片上传
    layui.use(['layer'], function () {
        var upload = layui.upload,
            $ = layui.$;
        let uploadInst = upload.render({
            elem: '#upload-mainDiagram'
            , url: '/meily/upload'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#mainDiagram').css({
                        'background-image': 'url(' + result + ')',
                        'background-size': '100% 100%'
                    }); //图片链接（base64）
                });
                layer.msg('上传中', {icon: 16, time: 0});
            }
            , done: function (res) {
                //如果上传失败
                if (res.code !== '200') {
                    return layer.msg('上传失败');
                }
                //上传成功的一些操作
                $('input[name="image"]').val(res.url);
                $('#errText').html(''); //置空上传失败的状态
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#errText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs upload-reload" style="margin-bottom: 5px">重试</a>');
                demoText.find('.upload-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
            //进度条
            , progress: function (n, elem, e) {
                if (n == 100) {
                    layer.msg('上传完毕', {icon: 1});
                }
            }
        });
    });

    // 富文本编辑器
    layui.use(['layer', 'wangEditor'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            wangEditor = layui.wangEditor;

        editor = new wangEditor('#editor');
        editor.customConfig.uploadImgServer = "/meily/upload";
        editor.customConfig.uploadFileName = 'file';
        editor.customConfig.pasteFilterStyle = false;
        editor.customConfig.uploadImgMaxLength = 5;
        editor.customConfig.uploadImgHooks = {
            // 上传超时
            timeout: function (xhr, editor) {
                layer.msg('上传超时！')
            },
            // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
            customInsert: function (insertImg, result, editor) {
                console.log(result);
                if (result.code == 200) {
                    var url = result.url;
                    insertImg(url);
                    // url.forEach(function (e) {
                    //     insertImg(e);
                    // })
                } else {
                    layer.msg(result.msg);
                }
            }
        };
        editor.customConfig.customAlert = function (info) {
            layer.msg(info);
        };
        editor.customConfig.onchange = function (html) {
            $('input[name="content"]').val(html);
        };
        editor.create();
    });


    /**
     * 初始化富文本编辑器
     */
    function initEditor(html) {
        editor.txt.html(html);
    }

    /**
     * 添加商品主图
     */
    function addPic() {
        layui.use(['layer', 'form'], function () {
            const layer = layui.layer
            layer.prompt({
                title: '请输入图片链接',
                btn: ['确定', '取消'],
                area: ['200px', '20px'],
                formType: 0
            }, function (text, index) {
                if (isNotNull(text)) {
                    $('#mainDiagram').css({
                        'background-image': 'url(' + text + ')',
                        'background-size': '100% 100%'
                    }); //图片链接（base64）
                    $('input[name="image"]').val(text);
                } else {
                    layer.msg("图片链接不能为空噢");
                }
                layer.close(index);
            });
        });
    }


    /**
     * 清空内容（包括源代码）
     */
    function emptyDetails() {
        editor.txt.clear();
        $('input[name="content"]').val('');
        layui.use(['layer'], function () {
            let $ = layui.$, layer = layui.layer;
            layer.msg("已清除！")
        })
    }

</script>
</body>
</html>
